// Copyright © 2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using CefSharp.WinForms.Example;
using CefSharp.WinForms.Example.Helper;
using MyCef;

namespace MyCef.Handlers
{
    /// <summary>
    ///1. 新的链接 弹出窗口的位置
    ///2. 新窗口位置
    /// </summary>
    public class LifeSpanHandler : ILifeSpanHandler
    {
        private readonly bool openPopupsAsTabs;

        private Dictionary<int, PopupAsChildHelper> popupasChildHelpers = new Dictionary<int, PopupAsChildHelper>();

        public LifeSpanHandler(bool openPopupsAsTabs)
        {
            this.openPopupsAsTabs = openPopupsAsTabs;
        }
        /// <summary>
        /// 弹出之前
        /// </summary>
        bool ILifeSpanHandler.OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
        {
            //NOTE: DevTools popups DO NOT trigger OnBeforePopup.

            //wpf常用，这里不用打开新窗口
            newBrowser = null;

            if (!openPopupsAsTabs)
            {
                return false;
            }

            var webBrowser = (ChromiumWebBrowser)chromiumWebBrowser;
            webBrowser.Invoke(new Action(() =>
            {
                //if (webBrowser.FindForm() is MainForm owner)
                //{
                //    var control = new Control
                //    {
                //        Dock = DockStyle.Fill
                //    };
                //    control.CreateControl();
                //    owner.CreatePageWebBrowser(targetUrl, control);
                //    var rect = control.ClientRectangle;
                //    windowInfo.SetAsChild(control.Handle, rect.Left, rect.Top, rect.Right, rect.Bottom);
                //}
                if (webBrowser.FindForm() is MainForm owner)
                {
                    owner.CreatePageWebBrowser(targetUrl, windowInfo);
                }
            }));
            return false;
        }
        /// <summary>
        /// 创建之后
        /// </summary>
        /// <param name="chromiumWebBrowser"></param>
        /// <param name="browser"></param>
        void ILifeSpanHandler.OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            if (browser.IsPopup)
            {
                var windowHandle = browser.GetHost().GetWindowHandle();
                //如果没有parentControl，那么很可能是CEF创建的本地弹出窗口(默认情况下，Devtools将作为弹出窗口打开，此时尚未设置Url）
                var parentControl = Control.FromChildHandle(windowHandle);
                if (parentControl != null)
                {
                    var interceptor = new PopupAsChildHelper(browser);
                    popupasChildHelpers.Add(browser.Identifier, interceptor);
                }
            }
        }

        bool ILifeSpanHandler.DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            var windowHandle = browser.GetHost().GetWindowHandle();
            var webBrowser = (ChromiumWebBrowser)chromiumWebBrowser;
            if (browser.MainFrame.Url.Equals("devtools://devtools/devtools_app.html"))
            {
                var parentControl = Control.FromChildHandle(windowHandle);
                if (parentControl == null)
                {
                    return false;
                }
                webBrowser.Invoke(new Action(() =>
                {
                    parentControl.Dispose();
                }));

                return true;
            }

            if (openPopupsAsTabs)
            {
                if (!webBrowser.IsDisposed && webBrowser.IsHandleCreated)
                {
                    webBrowser.Invoke(new Action(() =>
                    {
                        if (webBrowser.FindForm() is BrowserForm owner)
                        {
                            owner.RemoveTab(windowHandle);
                        }
                    }));
                }
                return true;
            }
            return false;
        }

        void ILifeSpanHandler.OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {
            if (!browser.IsDisposed && browser.IsPopup)
            {
                if (popupasChildHelpers.TryGetValue(browser.Identifier, out PopupAsChildHelper interceptor))
                {
                    popupasChildHelpers[browser.Identifier] = null;
                    interceptor.Dispose();
                }
            }
        }
    }
}
